/**
 * @author Endre Marczi
 * 
 * This UI handles everything that is related to the login process. 
 */

package ch.ffhs.radarpp;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import ch.ffhs.radarpp.managers.PersistentDataManager;
import ch.ffhs.radarpp.managers.WebRequestManager;
import ch.ffhs.radarpp.misc.BaseActivity;
import ch.ffhs.radarpp.model.LoginInformation;

public class LoginActivity extends BaseActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		LoginInformation login = PersistentDataManager.getLoginInfo(this);

		if (login != null) {
			editText(R.id.loginUI_username_input).setText(login.getUsername());
			editText(R.id.loginUI_password_input).setText(login.getPassword());

			onClick_login(null);
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	public void onClick_login(View button) {

		showWaitingMessage(getString(R.string.login_please_wait));

		String username = editText(R.id.loginUI_username_input).getText().toString();
		String password = editText(R.id.loginUI_password_input).getText().toString();

		getWebManager().executeHTTPRequest(WebRequestManager.createLoginRequest(this, username, password));

	}

	public void onClick_register(View button) {
		Intent i = new Intent(this, RegisterActivity.class);
		startActivity(i);
	}

	@Override
	public void requestCompleted(String result, Object context) {

		try {

			JSONObject object = new JSONObject(result);

			if (object.getBoolean(getString(R.string.loginresult_successfull))) {
				String username = editText(R.id.loginUI_username_input).getText().toString();
				String password = editText(R.id.loginUI_password_input).getText().toString();

				PersistentDataManager.setLoginInfo(this, new LoginInformation(username, password, object.getInt(getString(R.string.loginresult_userid))));

				Intent i = new Intent(this, FriendsListActivity.class);
				startActivity(i);

				closeMessage();

			} else {

				showMessage(getString(R.string.login_invalid));

			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

}
